/**
 *@description 用户登录后开启websock请求
 * */
import store from '../../store'
import { Notification } from 'element-ui';
import db from '../../../datastore'
import mqtt from 'mqtt'

var client
const options = {
    reconnectPeriod: 1000, // 1000毫秒，两次重新连接之间的间隔
    connectTimeout: 40000, // 40 * 1000毫秒，等待收到CONNACK的时间
    clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
    username: "",
    password: "",
    clean: true
}

let ws = null // websock
let heart = null // 心跳包定时器id
let isWrong = false // 标记是否密码错误
let isError = false // 标记是否连接错误
var temp = new Array(); // 重连数组

// 将重连信息移除
function removeTemp (obj) {
	console.log("重连信息")
  var id = obj.id;
  //将请求记录从 temp 中去掉
  for (var key in temp) {
    if (id == temp[key].id) {
      console.log("移除:" + temp[key].id);
      temp.slice(key, 1);
      break;
    }
  }
}

// 发送WebSocket请求
function wsSend (param, content) {
    console.log('client', param)
    client.publish(param, content, {qos: 2})
}

// 接收WebSocket返回信息
function wsOnMessage(topic, data) {
    console.log('客服列表:', topic, data)
   
    if (data.indexOf(';') != -1) {
        let dataArr = data.split(';')
        dataArr.pop()
        let num = Math.floor((Math.random()*dataArr.length));
        let _num = dataArr[num]
        console.log('_num', _num)
        wsSend('chating/history/' + _num, `${store.getters.uid}`)
        store.dispatch('user/updateKid', _num)
    } else {
        store.dispatch('user/updateKid', data)
        wsSend('chating/history/' + data, `${store.getters.uid}`)
    }
}

// 重连程序
function reconnect (obj) {
    var id = obj.id;
    //这可以写更多的重连逻辑，比如 每次重连间隔的时间增加
  
    // 1 账号密码错误不用重连
    if (isWrong) {
      return;
    }
  
    if (obj.reloadtimes == 10) {
      //将请求记录从 temp 中去掉
      removeTemp(obj);
    } else {
      obj.reloadtimes++;
      console.log(obj.id + "客服列表ws连接将在" + obj.reloadtimes + " 秒 后自动重新链接");
      setTimeout(() => {
        initkefulist(obj.id, 'ws://hz.tjanta.com:9001/mqtt', obj.data, obj.callback);
      }, obj.reloadtimes * 1000); //每次间隔时间递增
    }
  }


function initkefulist () {
    let loginData = store.getters.userInfo2;
    console.log('loginData', loginData)
    options.username = loginData.data.uid
    options.password = loginData.data.token
    // 获取url
    let nodeList = db
    .read()
    .get("trades.lineNode")
    .value();
    let loginUrl = nodeList.filter(v => v.selected)[0];
    client = mqtt.connect(loginUrl.node, options);
    client.on('connect', (e) => {
        // 客户聊天接收信息
        client.subscribe('customerSerOnline', {qos: 2}, (error) => {
            if (!error) {
                console.log('客服列表订阅成功')
            } else {
                console.log('客服列表订阅失败')
            }
        })
    })
    
    // 接收消息处理
    client.on('message', (topic, message) => {
        wsOnMessage(topic, message.toString())
    })
    // 断开发起重连
    client.on('reconnect', (error) => {
        console.log('正在重连:', error)
    })
    // 链接异常处理
    client.on('error', (error) => {
        console.log('连接失败:', error)
    })
}

export {
    reconnect,
  initkefulist,
  wsSend,
  wsOnMessage
}
